<?php

namespace app\index\service;

use app\common\model\LawCase;
use app\common\model\Trade;
use app\index\dao\LawCaseDao;
use app\index\model\UM as UM;
use ShidianUtil\Exception\DataNotExistException;
use think\Collection;

/**
 * Class LawCaseRushService
 * @package app\index\service
 */
class LawCaseRushService
{
    // dao
    private LawCaseDao $lawCaseDao;

    public function __construct(LawCaseDao $lawCaseDao)
    {
        $this->lawCaseDao = $lawCaseDao;
    }

    /**
     * 可抢购的案源-列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function index(UM $user, $rush, $cityId, $categoryId, $kw, ?int $page = null, ?int $page_size = null): Collection
    {
        if ($rush == 1) {
            return $this->lawCaseDao->selectCanRush($cityId, $categoryId, $kw, $page, $page_size);
        } else {
            return $this->lawCaseDao->selectRushed($user->id, $cityId, $categoryId, $kw, $page, $page_size);
        }
    }

    /**
     * 查询
     * @param UM|null $user
     * @param int $id
     * @return LawCase
     */
    public function read(UM $user, int $id): ?LawCase
    {
        $record = $this->lawCaseDao->findDetail($id);

        $trade = Trade::where('memberId', $user->id)
            ->where('tradeType', TRADE_LAS_CASE)
            ->where('payStatus', Trade::PAID)
            ->where('refundStatus', Trade::NOTREFUND)
            ->field(['id'])
            ->find();

        $isPay = $trade ? true : false;

        $record->isPay = $isPay ? 1 : 0;

        $phone = $record->phone;
        if (!$isPay) {
            $phone = mb_substr($phone, 0, 3) . '****' . mb_substr($phone, 7);
        }
        $record->phone = $phone;


        $priceArr = [];
        if ($record->surplus > 1) {
            $name = $record->surplus == $record->num ? '独享价格' : '剩余全买';
            $priceArr[] = [
                'name' => $name,
                'num' => $record->surplus,
                'price' => $record->price * $record->surplus,
            ];
        }
        if ($record->surplus > 0) {
            $priceArr[] = [
                'name' => '单次价格',
                'num' => 1,
                'price' => $record->price,
            ];
        }
        $record->priceArr = $priceArr;

        return $record;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return LawCase
     */
    public function modify(UM $user, int $id, array $params): LawCase
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = LawCase::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该对象不存在或已被删除');
        }

        $allowField = [];
        $this->lawCaseDao->updateActive($record, $params, $allowField);

        return $record;
    }

}
